package com.jstyle.beatecg.fragment;

import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.content.Context;
import android.content.DialogInterface;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;


import com.jstyle.beatecg.R;
import com.jstyle.beatecg.adapter.ScanDeviceAdapter;
import com.jstyle.beatecg.model.MyBluetoothDevice;
import com.jstyle.beatecg.util.LanguageHelp;
import com.jstyle.beatecg.util.ResolveData;
import com.jstyle.beatecg.util.ScreenUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link DeviceFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class DeviceFragment extends DialogFragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    @BindView(R.id.listView_device)
    ListView listViewDevice;
    @BindView(R.id.bt_scan_device)
    Button btScanDevice;
    Handler mHandler=new Handler();
    ScanDeviceAdapter deviceAdapter;
    private BluetoothAdapter mBluetoothAdapter;
    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private OnFragmentInteractionListener mListener;
    private boolean isScanning;

    public DeviceFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment DeviceFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static DeviceFragment newInstance(String param1, String param2) {
        DeviceFragment fragment = new DeviceFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);

        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);
        View view = inflater.inflate(R.layout.fragment_device, container, false);
        ButterKnife.bind(this, view);
        initView();
        return view;
    }
    List<BluetoothDevice> device=new ArrayList<>();
    private void initView() {
        LanguageHelp.changeAppLanguage(getActivity());
        final BluetoothManager bluetoothManager = (BluetoothManager) getActivity().getSystemService(Context.BLUETOOTH_SERVICE);
        mBluetoothAdapter = bluetoothManager.getAdapter();
        deviceAdapter=new ScanDeviceAdapter(getActivity());
        listViewDevice.setAdapter(deviceAdapter);
        listViewDevice.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if(mListener!=null){
                    startScan(false);
                    mListener.onFragmentInteraction(deviceAdapter.devices().get(position));
                }
            }
        });
        startScan(true);
    }
    @Override
    public void onStart() {
        super.onStart();
        int width= ScreenUtils.getScreenWidth(getActivity());
        getDialog().getWindow().setLayout( width,ViewGroup.LayoutParams.WRAP_CONTENT);
        getDialog().setCancelable(false);
    }
    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {

        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
        mHandler.removeCallbacksAndMessages(null);
    }

    @Override
    public void onDismiss(DialogInterface dialog) {
        super.onDismiss(dialog);
        deviceAdapter.clear();
        if(isScanning)
            startScan(false);
        mHandler.removeCallbacksAndMessages(null);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();

    }

    @OnClick(R.id.bt_scan_device)
    public void onClick() {

        startScan(!isScanning);
    }
    private void startScan(boolean enable) {
        // TODO Auto-generated method stub
        if (enable) {
            if (isAdded()) {
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    mBluetoothAdapter.stopLeScan(mLeScanCallback);
                    isScanning = false;
                    btScanDevice.setText(getResources().getString(
                            R.string.start_scan));
                }
            }, 60000);
            deviceAdapter.clear();
            mBluetoothAdapter.startLeScan(mLeScanCallback);
            isScanning = true;
            if ( btScanDevice != null) {
                btScanDevice.setText(getResources().getString(R.string.stop_scan));
            }}
        } else {
            if (isAdded()) {
                btScanDevice.setText(getResources().getString(R.string.start_scan));
                mBluetoothAdapter.stopLeScan(mLeScanCallback);
                isScanning = false;
                dismiss();
            }

        }
    }
    private BluetoothAdapter.LeScanCallback mLeScanCallback=new BluetoothAdapter.LeScanCallback() {
        @SuppressLint("NewApi")
        @Override
        public void onLeScan(final BluetoothDevice device, final int rssi, final byte[] scanRecord) {
            if(isAdded()){
                Objects.requireNonNull(getActivity()).runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        String name = device.getName();
                        if (!TextUtils.isEmpty(name)) {
                           if(name.trim().toLowerCase().contains("health")||name.trim().toLowerCase().contains("ecg")){
                               MyBluetoothDevice myBluDevice=new MyBluetoothDevice();
                               myBluDevice.setNames(name);
                               myBluDevice.setRssis(rssi);//信号量为负数转换为正数
                               myBluDevice.setDeviceAddress(device.getAddress());
                               deviceAdapter.addDevice(myBluDevice);
                           }
                        }
                    }
                });
            }


        }
    };
    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(MyBluetoothDevice myBluetoothDevice);
    }
}
